//# DBSyncHandler.js
//# NGJurassic
//#
//# Created by Washaq.Majeed on 7/13/11.
//# Copyright 2011 __MyCompanyName__. All rights reserved.

exports.DBSyncHandler = Core.Class.subclass(
{
											  
    initialize: function() 
    {
		this._successCB = null;
		this._existingDBPath = null;
		this._tempDBPath = "";
		this._resources = null;
        this._loadDBResourceSuccessCB = null;
		this._currentDBObjects = [];
		this._readCount = 0;
											  
    },
											
	loadExistingDBResource: function(existingDbPath,resources, loadDBResourceSuccess)
	{
		this._loadDBResourceSuccessCB = loadDBResourceSuccess;
		this._existingDbPath = existingDbPath;
		this._resources = resources;
        Storage.FileSystem.readFile(existingDbPath+'/temp/User.json',this.checkIfFileExistAtTempPath.bind(this));
		
	},
	checkIfFileExistAtTempPath: function(error,contents)
	{
		if(error)
		{
			this._tempDBPath = "";
		}
		else
		{
			this._tempDBPath = "/temp";
		}
		if(this._resources) {
            var length = this._resources.length;
            this._readCount = 0;
            
            if(length > 0) {
                var name = this._resources[0];
                Storage.FileSystem.readFile(this._existingDbPath+this._tempDBPath+'/'+name,this._dbFileReadCallback.bind(this,0));
            }
        }
		
	},
	
	_dbFileReadCallback: function (resourceIndex,error,contents){
		console.log('Zulu: DBSyncHandler::: dbFileReadCallback '+error);
		if(!error){
			var data = eval('('+ contents +')');
			
            var resourceName = this._resources[resourceIndex];
            
			if(resourceName == "User.json")
			{
				console.log('Zulu: Resource Name is User.json ');							
				var dbVersion = data.db_version;
				if(dbVersion == MM_VERSION_NUMBER)
				{
					delete data;
					delete contents;
					delete this._resources;
					this._resources = null;
					this._loadDBResourceSuccessCB();
					return;
				}
				else
				{
					data.db_version = MM_VERSION_NUMBER;
				}
			}
	        // Will execute in case of update Scenario
            this._currentDBObjects[resourceName] = data;
			if(this._tempDBPath == "")
			{
				console.log("Zulu: writeFile at temp ");
				var pathToResource = this._existingDbPath+"/temp" +"/"+ resourceName;							
				Storage.FileSystem.writeFile(pathToResource, contents);
			}
			
            this._readCount ++;
		} else {
			var resourceName = this._resources[resourceIndex];								
			if(resourceName == "User.json")
			{
				delete this._resources;
				this._resources = null;
				this._loadDBResourceSuccessCB();
				return;
			}
            this._resources.splice(resourceIndex,1);
        }
        
        var totalFiles = this._resources.length;
		if(this._readCount == totalFiles){
			this._loadDBResourceSuccessCB();
		} else {
            var name = this._resources[this._readCount];
			Storage.FileSystem.readFile(this._existingDbPath+this._tempDBPath+'/'+name,this._dbFileReadCallback.bind(this,this._readCount));
        }
	},
    
	startSynchingUserData: function(successCB)
	{
		console.log('>> startSynchingUserData ');
		this._successCB = successCB;
		if(this._resources && this._resources.length > 0)
		{
			this._creatBreedingFile();
			this._creatInventoryFile();
			this._creatQuestFile();
			this._creatMultiParkInfoFile();
			var count = this._resources.length, i = 0;
			for(; i < count ; i++)
			{
				var resourceName = this._resources[i];
				//console.log(">> wish resourceName "+resourceName);
				var currentResourceObj = this._currentDBObjects[resourceName]
				if(resourceName  == "Zoo1.json" || resourceName  == "DefaultZoo.json")
				{
					currentResourceObj.concessionId = 1;
					currentResourceObj.decorationId = 1;
					currentResourceObj.allConcessions = {};
					currentResourceObj.allDecorations = {};
				}
				var pathToResource = this._existingDbPath +"/"+ resourceName;
				//console.log(">> wish SAVED at: " + pathToResource);
				var jsonStr = JSON.stringify(currentResourceObj);
				//console.log(">> wishJSON string: " + jsonStr);
				Storage.FileSystem.writeFile(pathToResource, jsonStr);
				delete currentResourceObj;
			}
			
			var pathToResource = this._existingDbPath+'/temp' +"/"+ this._resources[0];	
			Storage.FileSystem.deleteFile(pathToResource,this._deleteFileCallback.bind(this,0));
			return;
			
			//this._readCount = 0;
			//var name = this._resources[0];
			//Storage.FileSystem.readFile(this._existingDbPath+'/'+name,this._dbReadCallback.bind(this,0));
		}
		else
		{
			this._successCB();
		}
		
	},
	_creatBreedingFile: function()
	{
		var breedingObj = {"classname":"Breeding","nextRoomID":2,"breedingRooms":{"1":{"breedingRoomStoreID":'10_1_1',"firstAnimalID":0,"secondAnimalID":0,"thirdAnimalID":0,"startingTime":0,"originalStartingTime":0}}};
		var pathToResource = this._existingDbPath +"/"+ "Breeding.json";
		//console.log("SAVED at: " + pathToResource);
		var jsonStr = JSON.stringify(breedingObj);
		//console.log("JSON string: " + jsonStr);
		Storage.FileSystem.writeFile(pathToResource, jsonStr);								
		delete breedingObj.breedingRooms["1"];
		delete breedingObj.breedingRooms;
		delete breedingObj;
		
	},
	_creatQuestFile: function()
	{
		var questObj = {"classname":"Quest","questId":1,"questItemId":1,"allQuests":[]};
		var pathToResource = this._existingDbPath +"/"+"Quest.json";
		//console.log("SAVED at: " + pathToResource);
		var jsonStr = JSON.stringify(questObj);
		//console.log("JSON string: " + jsonStr);
		Storage.FileSystem.writeFile(pathToResource, jsonStr);	
		delete questObj.allQuests;
		delete questObj;
	},
	_creatInventoryFile: function()
	{
		var inventoryObj = {"classname":"Inventory","questId":1, "allInventories":{}};
		var pathToResource = this._existingDbPath +"/"+"Inventory.json";
		//console.log("SAVED at: " + pathToResource);
		var jsonStr = JSON.stringify(inventoryObj);
		//console.log("JSON string: " + jsonStr);
		Storage.FileSystem.writeFile(pathToResource, jsonStr);	
		delete inventoryObj.allInventories;
		delete inventoryObj;
	},
	
	_creatMultiParkInfoFile: function()
	{
		var multiParkInfoObj = {"classname":"MultiParkInfo","animalInfo":{"1_5_1":1},"allZooInfo":{}};
		var pathToResource = this._existingDbPath +"/"+"MultiParkInfo.json";
		//console.log("SAVED at: " + pathToResource);
		var jsonStr = JSON.stringify(multiParkInfoObj);
		//console.log("JSON string: " + jsonStr);
		Storage.FileSystem.writeFile(pathToResource, jsonStr);	
		delete multiParkInfoObj.animalInfo;
		delete multiParkInfoObj.allZooInfo;
		delete multiParkInfoObj;
	},
	
    _dbReadCallback: function (resourceIndex,error,contents){
		console.log('>> _dbReadCallback 2222');
		if(!error){
			var data = eval('('+ contents +')');
			var name = this._resources[resourceIndex];								
			var currentResourceObj = this._currentDBObjects[name], id;
			for(id in data)
			{
				data[id] = currentResourceObj[id];
			
			}
			var pathToResource = this._existingDbPath +"/"+ name;
			//console.log("SAVED at: " + pathToResource);
			var jsonStr = JSON.stringify(data);
			//console.log("JSON string: " + jsonStr);
			Storage.FileSystem.writeFile(pathToResource, jsonStr);
            
			delete currentResourceObj;
			delete data;
			delete contents;
		}
		this._readCount ++;
        
        var totalFiles = this._resources.length;
		if(this._readCount == totalFiles){
			var pathToResource = this._existingDbPath+'/temp' +"/"+ this._resources[0];	
			Storage.FileSystem.deleteFile(pathToResource,this._deleteFileCallback.bind(this,0));
			//this._successCB();
		} else {
            var name = this._resources[this._readCount];
            Storage.FileSystem.readFile(this._existingDbPath+'/'+name,this._dbReadCallback.bind(this,this._readCount));
        }
	},
	_deleteFileCallback: function(fileIndex, error,data){
		fileIndex ++;
		//if(error){
//			this._deleteError = true;
//		}
		var length = this._resources.length;
		if(fileIndex == length){
			this._successCB();
			//if(this._deleteError){
//				this._deleteError = false;
//				//this.errorCallback();
//			}
//			else{
//				this._successCB();
//			}
		}else {
            var pathToResource = this._existingDbPath+'/temp' +"/"+ this._resources[fileIndex];	
			Storage.FileSystem.deleteFile(pathToResource,this._deleteFileCallback.bind(this,fileIndex));
        }
	},
    
	destroy: function()
    {
		if(this._resources)
		{
			delete this._resources;
		}
		if(this._currentDBObjects)
		{
			delete this._currentDBObjects;
		}
	},
	
	
});